// src/pages/Login/index.tsx

import React, { useState } from "react";
import { useAppDispatch } from "@store/hooks";
import { login } from "@store/modules/userSlice";
import { useNavigate, useLocation } from "react-router-dom";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Card, Typography } from "antd";
import "./login.less";

const { Title } = Typography;

const Login: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);

  // 从路由参数 query 中取到重定向地址，若无则默认指向 "/"
  const from = (location.state as any)?.from?.pathname || "/";

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      const result = await dispatch(login(values)).unwrap();
      // 登录成功后，继续拉取用户信息
      await dispatch(fetchUserInfo());
      navigate(from, { replace: true });
    } catch (error) {
      // 登录失败逻辑：已经由 slice 中 message.error 处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <Card className="login-card">
        <Title level={3} style={{ textAlign: "center" }}>
          管理系统登录
        </Title>
        <Form name="loginForm" onFinish={onFinish} layout="vertical">
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="用户名"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password
              prefix={<LockOutlined className="site-form-item-icon" />}
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
              block
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
